//go:build darwin
// +build darwin

package printer

import (
	"errors"
	"os/exec"
	"strings"
	"sync"
)

var (
	manager PrinterManager
	once    sync.Once
)

func GetManager() PrinterManager {
	once.Do(func() {
		manager = newDarwinManager()
	})
	return manager
}

type darwinManager struct{}

func newDarwinManager() PrinterManager {
	return &darwinManager{}
}

func (d *darwinManager) ListPrinters() ([]Printer, error) {
	out, err := exec.Command("lpstat", "-p").Output()
	if err != nil {
		return nil, err
	}
	lines := strings.Split(string(out), "\n")
	list := []Printer{}
	for _, line := range lines {
		if strings.HasPrefix(line, "printer ") {
			parts := strings.Fields(line)
			if len(parts) >= 2 {
				list = append(list, Printer{Name: parts[1], Status: "online", IsDefault: false})
			}
		}
	}
	return list, nil
}

func (d *darwinManager) GetPrinterOptions(name string) (PrinterOptions, error) {
	return PrinterOptions{
		PaperSizes:   []string{"A4", "A5", "Letter"},
		Orientations: []string{"portrait", "landscape"},
		Copies:       CopiesRange{Min: 1, Max: 99},
	}, nil
}

func (d *darwinManager) SubmitPrintJob(req PrintJobRequest) ([]int, error) {
	if len(req.Files) == 0 {
		return nil, errors.New("no files to print")
	}
	// 解析自定义纸张尺寸
	if req.Options["paperSize"] == "custom" {
		length, _ := req.Options["length"].(float64)
		width, _ := req.Options["width"].(float64)
		_ = length
		_ = width
		// TODO: 实际打印时用 length/width 设置纸张尺寸
		// 可加日志：fmt.Printf("[打印] 自定义纸张 长:%.2fmm 宽:%.2fmm\n", length, width)
	}
	ids := []int{}
	for i, f := range req.Files {
		// TODO: Base64解码写入临时文件，然后用lp命令打印
		_ = f
		ids = append(ids, 2000+i)
	}
	return ids, nil
}

func (d *darwinManager) GetPrintJobStatus(jobId int) (PrintJobStatus, error) {
	return PrintJobStatus{JobId: jobId, Status: "submitted", Message: "任务已提交"}, nil
}
